//
//  BRUserManager.m
//  BrezzeSaaS
//
//  Created by IOS on 2021/9/1.
//  Copyright © 2021 Brezze GWG. All rights reserved.
//

#import "BRUserManager.h"
#import "AppDelegate.h"

#define kIsLoginKey @"brezzeIsLogin"
#define kLoginTenantId @"kLoginTenantId"
#define kTokenKey @"brezzeIsTokenGlobal"
#define kBRConfigKey @"kBRConfigKeys"
#define kLoginTypeKey @"kLoginTypeKey"

#define kLoginPhoneKey @"kLoginPhoneKey"
#define kLoginCodeKey @"kLoginCodeKey"
#define kLoginEmailKey @"kLoginEmailKey"

#define kGlobalLatitudeKey @"kGlobalLatitudeKey"
#define kGlobalLongitudeKey @"kGlobalLongitudeKey"
// 默认位置：越南胡志明市
#define kDefaultLatitude 10.8231
#define kDefaultLongitude 106.6297

@implementation BRUserManager

+ (instancetype)share {
    static BRUserManager *man = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        man = [[BRUserManager alloc] init];
    });
    return man;
}

- (void)logoutClean {
    // 清除登录状态
    USERManager.isLogin = NO;
    
    // 清除租户信息
    USERManager.tenantModel = [BRTenantModel new];
    
    // 清除Token（从NSUserDefaults中删除）
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kTokenKey];
    
    // 清除登录状态标记（从NSUserDefaults中删除）
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kIsLoginKey];
    
    // 清除登录相关的用户信息
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kLoginTenantId];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kLoginPhoneKey];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kLoginCodeKey];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kLoginEmailKey];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kLoginTypeKey];
    
    // 同步NSUserDefaults
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    // 清除缓存的用户模型
    [[BRCacheManager share] removeObj:kBRUserKey];
    
    // 取消通知订阅
    [BRNotificationManager unsubNoti:USERManager.userNotiKey status:^(BOOL isSucc) {
            
    }];
    
    NSLog(@"✅ 退出登录：已清除所有用户信息和Token");
}

- (NSString *)userNotiKey {
    return [NSString stringWithFormat:@"%@_%@",kAllDeviceNotiKey,USERManager.token];
}

- (void)toChangeRootVC {
    AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [app didInitWindow];
}

- (void)logout:(void(^)(void))succ faile:(void(^)(void))faile {
    
    [[self class] logoutRequest:^{
        [self logoutClean];
        if (succ) {
            succ();
        }
    } faile:^{
        [self logoutClean];
        if (faile) {
            faile();
        }
    }];
}

- (NSString *)token {
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:kTokenKey]) {
        return [[NSUserDefaults standardUserDefaults] stringForKey:kTokenKey];
    }
    
    return @"";
}

-  (void)setToken:(NSString *)token {
    [[NSUserDefaults standardUserDefaults] setValue:token forKey:kTokenKey];
    [[NSUserDefaults  standardUserDefaults] synchronize];
    
    // 添加调试信息
    NSLog(@"🔑 Token已更新: %@", token.length > 0 ? [NSString stringWithFormat:@"%@...", [token substringToIndex:MIN(10, token.length)]] : @"空");
    [self br_logUserStatus];
}

- (BOOL)isLogin {
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:kIsLoginKey]) {
        BOOL loginStatus = [[NSUserDefaults standardUserDefaults] boolForKey:kIsLoginKey];
        NSLog(@"🔍 从NSUserDefaults读取登录状态: %@", loginStatus ? @"已登录" : @"未登录");
        return loginStatus;
    }
    
    NSLog(@"🔍 NSUserDefaults中没有登录状态记录，返回未登录");
    return NO;
}

- (void)setIsLogin:(BOOL)isLogin {
    
    [[NSUserDefaults standardUserDefaults] setBool:isLogin forKey:kIsLoginKey];
    [[NSUserDefaults  standardUserDefaults] synchronize];
    
    // 添加调试信息
    NSLog(@"🔐 登录状态已更新: %@", isLogin ? @"已登录" : @"未登录");
    [self br_logUserStatus];
}

- (NSString *)loginTenantId {
    if ([[NSUserDefaults standardUserDefaults] objectForKey:kLoginTenantId]) {
        return [[NSUserDefaults standardUserDefaults] stringForKey:kLoginTenantId];
    }
    
    return @"";
}

- (void)setLoginTenantId:(NSString *)loginTenantId {
    [[NSUserDefaults standardUserDefaults] setValue:loginTenantId forKey:kLoginTenantId];
    [[NSUserDefaults  standardUserDefaults] synchronize];
}

#pragma mark - GET && SET --
- (void)setUserModel:(BRUserModel *)userModel {
    [[BRCacheManager share] save:userModel tableName:kBRUserKey];
}

- (void)setConfigs:(NSArray<BRConfigModel *> *)configs {
    [[BRCacheManager share] save:configs tableName:kBRConfigKey];
}

- (void)setTenantModel:(BRTenantModel *)tenantModel {
    [[BRCacheManager share] save:tenantModel tableName:kTenantKey];
}

- (void)setTenantList:(NSArray *)tenantList {
    [[BRCacheManager share] save:tenantList tableName:kTenantListKey];
}

- (NSArray *)tenantList {
    if ([[BRCacheManager share] hasValueForKey:kTenantListKey]) {
        return  (NSArray *)[[BRCacheManager share] getValue:kTenantListKey];
    }
    return @[];
}

- (BRTenantModel *)tenantModel {
    if ([[BRCacheManager share] hasValueForKey:kTenantKey]) {
        return  (BRTenantModel *)[[BRCacheManager share] getValue:kTenantKey];
    }
    return [BRTenantModel new];
}

- (BRUserModel *)userModel {
    if ([[BRCacheManager share] hasValueForKey:kBRUserKey]) {
        return  (BRUserModel *)[[BRCacheManager share] getValue:kBRUserKey];
    }
    return [BRUserModel new];
}

- (NSArray<BRConfigModel *> *)configs {
    
    if ([[BRCacheManager share] hasValueForKey:kBRConfigKey]) {
        return  (NSArray *)[[BRCacheManager share] getValue:kBRConfigKey];
    }
    return @[];
}

- (NSInteger)loginType {
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:kLoginTypeKey]) {
        NSNumber *loginType = (NSNumber *)[[NSUserDefaults standardUserDefaults] objectForKey:kLoginTypeKey];
        return loginType.integerValue;
    }
    return 0;
}

- (void)setLoginType:(NSInteger)loginType {
    
    [[NSUserDefaults standardUserDefaults] setObject:@(loginType) forKey:kLoginTypeKey];
    [[NSUserDefaults  standardUserDefaults] synchronize];
}

- (NSString *)filesSever {
    
    if (!BR_StringIsEmpty(_filesSever)) {
        return _filesSever;
    }
    
    for (BRConfigModel *model in [BRUserManager share].configs) {
        if ([model.key isEqualToString:@"file-host"]) {
            return model.value;
        }
    }
    return BASE_URL;
}

- (NSString *)branchId {
    
    if (!_branchId) {
        return @"";
    }
    
    return _branchId;
}

- (NSString *)invitationUrl {
    
    if (!BR_StringIsEmpty(_invitationUrl)) {
        return _invitationUrl;
    }
    
    for (BRConfigModel *model in [BRUserManager share].configs) {
        if ([model.key isEqualToString:@"invitation"]) {
            return model.value;
        }
    }
    return @"";
}

- (NSString *)contactPhone {
    
    if (!BR_StringIsEmpty(_contactPhone)) {
        return _contactPhone;
    }
    
    for (BRConfigModel *model in [BRUserManager share].configs) {
        if ([model.key isEqualToString:@"hotline"]) {
            return model.value;
        }
    }
    return @"";
}

- (NSString *)contactEmail {
    if (!BR_StringIsEmpty(_contactEmail)) {
        return _contactEmail;
    }
    
    for (BRConfigModel *model in [BRUserManager share].configs) {
        if ([model.key isEqualToString:@"email"]) {
            return model.value;
        }
    }
    return @"";
}

- (NSString *)rentRule {
    if (self.ruleModel) {
 
        BRRuleModel *dto = self.ruleModel;
        
        return [self br_ruleOfModel:dto];
    }
    
    return @"";
}

- (NSString *)br_ruleOfModel:(BRRuleModel *)dto {
    
    
    if (dto.isSystem) {
        return Localized(@"time_freeUsage");
    }
    
//    NSString *symbol = [self.currency uppercaseString];
    NSString *controlType = [self br_controlType:dto.controlType inCycle:dto.cycle]; //计费周期期限类型: 1-分 2-小时 3-天
    NSString *freeDurationControlType = [self br_controlType:dto.freeDurationControlType inCycle:dto.freeDuration]; //计费周期期限类型: 1-分 2-小时 3-天
    NSString *maxDurationControlType = [self br_controlType:dto.maxDurationControlType inCycle:dto.maxRentDuration]; //最大时长: 1-分 2-小时 3-天

    BOOL hasFree = dto.freeDuration != 0 ; //免费时间
    BOOL hasDaily = dto.dayAmount.floatValue != 0 ; //每天封顶
    
    NSString *orderType = [self br_orderDally:dto.freeLimit];
//
//    NSString *freeTime = [self br_minOf:dto.freeDuration];
//
//    NSString *maxTime = [self br_hourOf:dto.maxRentDuration];
    
   /**
    5 mins free every order,
    %ld %@ %@,
    USD 1.00 per 30 mins
    %@ %.2f per %ld %@
    , daily cap is USD 8.00
    , daily cap is %@ %.2f
    . Total cap USD 16.00，maximum lease duration 72 hours.
    . Total cap %@ %.2f，maximum lease duration %ld %@.
    */
    NSString *orderRule = [NSString stringWithFormat:Localized(orderType),dto.freeDuration,freeDurationControlType];
    NSString *perRule = [NSString stringWithFormat:Localized(@"rule_perTime"),[BRPayManager br_amount:dto.amount],dto.cycle,controlType];
    NSString *dailyRule = [NSString stringWithFormat:Localized(@"rule_dailyCap"),[BRPayManager br_amount:dto.dayAmount]];
    
    NSString *maxRule = [NSString stringWithFormat:Localized(@"rule_totalCap"),[BRPayManager br_amount:dto.penaltyAmount],dto.maxRentDuration,maxDurationControlType];
    
    NSString *ruleStr = @"";
    if (hasFree) {
        ruleStr = orderRule;
        perRule = [NSString stringWithFormat:Localized(@"rule_perTimeAfter"),[BRPayManager br_amount:dto.amount],dto.cycle,controlType];
    }
    ruleStr = [NSString stringWithFormat:@"%@%@",ruleStr,perRule];
    if (hasDaily) ruleStr = [NSString stringWithFormat:@"%@%@",ruleStr,dailyRule];
    return [NSString stringWithFormat:@"%@%@",ruleStr,maxRule];
    
    
}

- (NSString *)br_controlType:(NSInteger)type inCycle:(NSInteger)cycle {
//    计费周期期限类型：1-分 2-小时 3-天
    if (type == 3)  return [self br_dayOf:cycle];
    if (type == 2)  return [self br_hourOf:cycle];
    return [self br_minOf:cycle];
}

- (NSString *)br_hourOf:(NSInteger)num {
//    计费周期期限类型：1-分 2-小时 3-天
    if (num > 1)  return Localized(@"time_hours");
    return Localized(@"time_hour");
}
- (NSString *)br_minOf:(NSInteger)num {

    if (num > 1)  return Localized(@"time_mins");
    return Localized(@"time_min");
}
- (NSString *)br_dayOf:(NSInteger)num {
//    计费周期期限类型：1-分 2-小时 3-天
    if (num > 1)  return Localized(@"time_days");
    return Localized(@"time_day");
}
/// 0: 不限
- (NSString *)br_orderDally:(NSInteger)nums {
    
    if (nums > 5) return [NSString stringWithFormat:@"first %ld orders daily",nums];
    NSString *str = [NSString stringWithFormat:@"time_dayOrder%ld",nums];
    
    return str;
}

- (NSString *)priceSymbol {
    
    NSDictionary *dic = [self.currencyJson mj_JSONObject];
    if (BR_DictIsEmpty(dic)) {
        return @"€";
    }
    return dic[@"symbol"];
}

- (NSString *)country {
    NSDictionary *dic = [self.currencyJson mj_JSONObject];
    if (BR_DictIsEmpty(dic)) {
        return @"";
    }
    return dic[@"country"];
}

- (NSString *)currency {
    NSDictionary *dic = [self.currencyJson mj_JSONObject];
    if (BR_DictIsEmpty(dic)) {
        return @"EUR";
    }
    return dic[@"currency"];
}

- (NSDecimalNumber *)lostPrice {
    
    if (_lostPrice.floatValue > 0) {
        return _lostPrice;
    }
    
    for (BRConfigModel *model in [BRUserManager share].configs) {
        if ([model.key isEqualToString:@"penalty-amount"]) {
            return [NSDecimalNumber decimalNumberWithString:model.value];
        }
    }
    
    return [NSDecimalNumber decimalNumberWithString:@"40.00"];
}

- (NSString *)valueOfConfig:(NSString *)key {
    
    for (BRConfigModel *model in self.configs) {
        if ([model.key isEqualToString:key]) {
            return model.value;
        }
    }
    return @"";
}

- (NSString *)termsOfUse {
    if (_termsOfUse.length > 0 ) {
        return _termsOfUse;
    }
    
    return [self valueOfConfig:@"terms-of-use"];
}

- (NSString *)privacyPolicy {
    if (_privacyPolicy.length > 0 ) {
        return _privacyPolicy;
    }
    
    return [self valueOfConfig:@"privacy-policy"];
}

- (NSString *)preAuthorizationPolicy {
    if (_preAuthorizationPolicy.length > 0 ) {
        return _preAuthorizationPolicy;
    }
    
    return [self valueOfConfig:@"pre-authorization-policy"];
}

- (BRRewardSwitchModel *)rewardSwitchModel {
    
    NSDictionary *dic = [self.rewardsSwitchJson mj_JSONObject];
    if (BR_DictIsEmpty(dic)) {
        return [BRRewardSwitchModel new];
    }
    return [BRRewardSwitchModel mj_objectWithKeyValues:dic[@"reward"]];
}

#pragma mark - 调试信息 --
- (void)br_logUserStatus {
    NSLog(@"📊 ========== 用户状态调试信息 ==========");
    NSLog(@"🔐 登录状态: %@", self.isLogin ? @"已登录" : @"未登录");
    NSLog(@"🔑 Token: %@", self.token.length > 0 ? [NSString stringWithFormat:@"%@...", [self.token substringToIndex:MIN(10, self.token.length)]] : @"空");
    NSLog(@"🏢 租户ID: %@", self.loginTenantId.length > 0 ? self.loginTenantId : @"空");
    NSLog(@"📱 用户手机: %@", self.loginPhone.length > 0 ? self.loginPhone : @"空");
    NSLog(@"📧 用户邮箱: %@", self.loginEmail.length > 0 ? self.loginEmail : @"空");
    
    // 检查NSUserDefaults中的原始值
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSLog(@"🔍 NSUserDefaults原始值检查:");
    NSLog(@"   - kIsLoginKey (%@): %@", kIsLoginKey, [defaults objectForKey:kIsLoginKey]);
    NSLog(@"   - kTokenKey (%@): %@", kTokenKey, [defaults objectForKey:kTokenKey]);
    NSLog(@"   - kLoginTenantId (%@): %@", kLoginTenantId, [defaults objectForKey:kLoginTenantId]);
    
    NSLog(@"📊 ======================================");
}



#pragma mark - 记录登录信息--
- (void)setLoginCode:(NSString *)loginCode {
    [[NSUserDefaults standardUserDefaults] setValue:loginCode forKey:kLoginCodeKey];
    [[NSUserDefaults  standardUserDefaults] synchronize];
    
}

- (NSString *)loginCode {
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:kLoginCodeKey]) {
        NSString *loginType = [[NSUserDefaults standardUserDefaults] stringForKey:kLoginCodeKey];
        return loginType;
    }
    return @"";
}

- (void)setLoginEmail:(NSString *)loginEmail {
    [[NSUserDefaults standardUserDefaults] setValue:loginEmail forKey:kLoginEmailKey];
    [[NSUserDefaults  standardUserDefaults] synchronize];
}

- (NSString *)loginEmail {
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:kLoginEmailKey]) {
        NSString *loginType = [[NSUserDefaults standardUserDefaults] stringForKey:kLoginEmailKey];
        return loginType;
    }
    return @"";
}

- (void)setLoginPhone:(NSString *)loginPhone {
    [[NSUserDefaults standardUserDefaults] setValue:loginPhone forKey:kLoginPhoneKey];
    [[NSUserDefaults  standardUserDefaults] synchronize];
}

- (NSString *)loginPhone {
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:kLoginPhoneKey]) {
        NSString *loginType = [[NSUserDefaults standardUserDefaults] stringForKey:kLoginPhoneKey];
        return loginType;
    }
    return @"";
}

#pragma mark - 请求配置相关 --
+ (void)requestUserInfo:(void(^)(void))succ faile:(void(^)(void))faile {
    
    [[BRRequestManager shared] GET:[BRAPI userInfo] params:nil succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        NSDictionary *dic = (NSDictionary *)dataDict[@"data"];
        BRUserModel  *model = [BRUserModel mj_objectWithKeyValues:dic];
        [BRUserManager share].userModel = model;
        
        if ([GGFaceIdManManage shareManage].needSave) {
            // 根据操作判断是否需要缓存当前信息
            [GGFaceIdManManage gg_saveData];

        }
        
        if (succ) {
            succ();
        }
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        if (faile) {
            faile();
        }
    }];
}

/// 获取用户详细信息（新接口）
+ (void)requestUserCenterInfo:(void(^)(void))succ faile:(void(^)(void))faile {
    
    [[BRRequestManager shared] GET:[BRAPI userCenterInfo] params:nil succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        NSLog(@"📋 用户详细信息返回: %@", dataDict);
        
        // 处理返回的数据
        NSDictionary *userDic = dataDict[@"user"];
        if (userDic && [userDic isKindOfClass:[NSDictionary class]]) {
            // 创建或更新用户模型
            BRUserModel *model = [BRUserModel mj_objectWithKeyValues:userDic];
            if (model) {
                [BRUserManager share].userModel = model;
                NSLog(@"✅ 用户信息已更新: userId=%@, nickName=%@, mobile=%@", 
                      model.userId ?: @"", 
                      model.nickName ?: @"", 
                      model.mobile ?: @"");
            }
        }
        
        // 处理其他信息（如语言列表、当前语言等）
        if (dataDict[@"currentLanguage"]) {
            // 可以更新当前语言设置
            NSString *currentLanguage = dataDict[@"currentLanguage"];
            NSLog(@"🌐 当前语言: %@", currentLanguage);
        }
        
        if (dataDict[@"languages"] && [dataDict[@"languages"] isKindOfClass:[NSArray class]]) {
            NSArray *languages = dataDict[@"languages"];
            NSLog(@"🌐 支持的语言列表: %@", languages);
        }
        
        if (succ) {
            succ();
        }
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        NSLog(@"❌ 获取用户详细信息失败: code=%ld, msg=%@", code, errMsg);
        if (faile) {
            faile();
        }
    }];
}

+ (void)requestConfigs:(void(^)(void))succ faile:(void(^)(void))faile {
    
    // 接口已废弃，注释掉调用
    /*
    [[BRRequestManager shared] GET:[BRAPI configs] params:nil succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        NSArray *configs = [BRConfigModel mj_objectArrayWithKeyValuesArray:dataDict[@"data"]];
        for (BRConfigModel *model in configs) {
            if ([model.key isEqualToString:@"currency"]) {
                
                [BRUserManager share].currencyJson = model.value;
            }
            if ([model.key isEqualToString:@"pre-authorization-policy"]) {
                
                [BRUserManager share].preAuthorizationPolicy = model.value;
            }
            if ([model.key isEqualToString:@"privacy-policy"]) {
                
                [BRUserManager share].privacyPolicy = model.value;
            }
            if ([model.key isEqualToString:@"terms-of-use"]) {
                
                [BRUserManager share].termsOfUse = model.value;
            }
            if ([model.key isEqualToString:@"deposit-policy"]) {
                
                [BRUserManager share].depositPolicy = model.value;
            }
            if ([model.key isEqualToString:@"penalty-amount"]) {
                [BRUserManager share].lostPrice = [NSDecimalNumber decimalNumberWithString:model.value];
            }
            if ([model.key isEqualToString:@"email"]) {
                [BRUserManager share].contactEmail = model.value;
            }
            if ([model.key isEqualToString:@"hotline"]) {
                [BRUserManager share].contactPhone = model.value;
            }
            if ([model.key isEqualToString:@"weChant-qr-code"]) {
                [BRUserManager share].qrCodeWX = model.value;
            }
            if ([model.key isEqualToString:@"whatsapp"]) {
                [BRUserManager share].whatsapp = model.value;
            }
            if ([model.key isEqualToString:@"zalo-qr-code"]) {
                [BRUserManager share].qrCodeZalo = model.value;
            }
            if ([model.key isEqualToString:@"file-host"]) {
                [BRUserManager share].filesSever = model.value;
            }
            if ([model.key isEqualToString:@"invitation"]) {
                [BRUserManager share].invitationUrl = model.value;
            }
            if ([model.key isEqualToString:@"switch-rewards"]) {
                [BRUserManager share].rewardsSwitchJson = model.value;
            }
            if ([model.key isEqualToString:@"switch-invite"]) {
                [BRUserManager share].switchInvite = model.value.integerValue;
            }

        }
        [BRUserManager share].configs = configs;
        if (succ) {
            succ();
        }
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        if (faile) {
            faile();
        }
    }];
    */
}

+ (void)requestPoints:(void(^)(void))succ faile:(void(^)(void))faile {
    
    [[BRRequestManager shared] GET:[BRAPI myPoints] params:nil succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        NSDictionary *dic = dataDict[@"data"];
        NSInteger point = 0;
        if (!BR_DictIsEmpty(dic)) {
            if ([dic[@"point"] isKindOfClass:[NSNumber class]]) {
                point = [dic[@"point"] integerValue];
            }
        }
        NSLog(@"获取积分 = 【%ld】 ",point);
        [BRUserManager share].point = point;
        if (succ) {
            succ();
        }
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        
        if (faile) {
            faile();
        }
    }];
    
}

+ (void)logoutRequest:(void(^)(void))succ faile:(void(^)(void))faile {
    
    // 注释掉退出登录接口调用（接口已废弃：https://s.youdianstar.com/api/login/log-out）
    // [[BRRequestManager shared] DELETE:[BRAPI logout] params:nil succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
    //     NSLog(@"接口退出 成功 ");
    //     if (succ) {
    //         succ();
    //     }
    // } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
    //     NSLog(@"接口退出 失败 ");
    //     if (faile) {
    //         faile();
    //     }
    // }];
    
    // 直接执行成功回调（因为接口已废弃，直接清除本地数据即可）
    NSLog(@"⚠️ 退出登录接口已废弃，直接清除本地数据");
    if (succ) {
        succ();
    }
    
}

+ (void)getWallet:(void(^)(NSDictionary *dataDict, NSInteger respCode))succeed failed:(void(^)(NSInteger code,NSString *errMsg))failed {
    [[BRRequestManager shared] GET:[BRAPI getWallet] params:nil succeed:succeed failed:failed];
    
}

+ (void)requestRule:(void (^)(void))succ faile:(void (^)(void))faile {
    
    [[BRRequestManager shared] GET:[BRAPI orderBilling] params:nil succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        NSDictionary *ruleDic = dataDict[@"data"];
        if ([ruleDic isKindOfClass:[NSDictionary class]]) {
            NSDictionary *billingDic = ruleDic[@"billing"];
            if ([billingDic isKindOfClass:[NSDictionary class]]) {
                BRRuleModel *model = [BRRuleModel  mj_objectWithKeyValues:billingDic];
                [BRUserManager share].ruleModel = model;
                if (succ) {
                    succ();
                }
                NSLog(@"获取计费规则-成功");
                return;
            }
        }
        NSLog(@"获取计费规则-失败");
        if (faile) {
            faile();
        }
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        if (faile) {
            faile();
        }
        NSLog(@"获取计费规则-失败");
    }];
}

+ (void)loginPlatformRequest:(NSDictionary *)req succ:(void (^)(void))succ faile:(void (^)(void))faile {
    
    [[BRRequestManager shared] PUT:[BRAPI platformSwitch] params:req succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        BRTenantModel *model = [BRTenantModel mj_objectWithKeyValues:dataDict[@"data"]];
        
        [BRUserManager share].tenantModel = model;
        [BRUserManager share].loginTenantId = model.platformId;
        
//        dispatch_async(dispatch_get_main_queue(), ^{
//            // 修改布局
//            [BRUserManager changTenantStyle:model.style.integerValue];
//        });
        
        // 同时更新配置 需先更新tenant再获取配置
        [BRUserManager requestConfigs:^{
            
        } faile:^{
            
        }];
        
        [BRUserManager requestUserInfo:^{
            
        } faile:^{
            
        }];
        
        [BRUserManager save:model];
        
        if (succ) {
            succ();
        }
        NSLog(@"平台切换-成功->%@[%@]",model.title,model.style);
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        if (faile) {
            faile();
        }
        NSLog(@"平台切换-失败");
    }];
}

+ (void)changTenantStyle:(NSInteger)tenantId {
    NSLog(@"平台切换-成功->[%ld]",tenantId);
    // brs=1 ,banana=5， bod=2 bst=6 坦桑尼亚 = 7
//    if (tenantId == 1) {
//        QMUIThemeManagerCenter.defaultThemeManager.currentThemeIdentifier = QDThemeIdentifierDark;
//        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
//    }else if (tenantId == 5) {
//        QMUIThemeManagerCenter.defaultThemeManager.currentThemeIdentifier = QDThemeIdentifierGrass;
//        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDarkContent;
//
//    }else if (tenantId == 6) {
//        QMUIThemeManagerCenter.defaultThemeManager.currentThemeIdentifier = QDThemeIdentifierBST;
//        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDarkContent;
//
//    }else if (tenantId == 7) {
//        QMUIThemeManagerCenter.defaultThemeManager.currentThemeIdentifier = QDThemeIdentifierTanzania;
//        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDarkContent;
//
//    }else if (tenantId == 8) {
//        QMUIThemeManagerCenter.defaultThemeManager.currentThemeIdentifier = QDThemeIdentifierIBoom;
//        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDarkContent;
//
//    } else {
        QMUIThemeManagerCenter.defaultThemeManager.currentThemeIdentifier = QDThemeIdentifierDefault;
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDarkContent;
//    }
    
    kNotifyPost(kNotiHomeChangeDark);
}

+ (void)save:(BRTenantModel *)model {
    NSMutableArray *arr = [NSMutableArray arrayWithArray:USERManager.tenantList];
    
    for (int i = 0; i < arr.count; i++) {
        BRTenantModel *oModel = arr[i];
        if ([oModel.platformId isEqualToString:model.platformId]) {
            
            [arr removeObjectAtIndex:i];
            [arr insertObject:model atIndex:0];
            
            USERManager.tenantList = arr;
            return;
        }
    }
    
    [arr insertObject:model atIndex:0];
    if (arr.count > 3) {
        [arr removeObjectAtIndex:arr.count - 1];
    }
    USERManager.tenantList = arr;
}


@end
